package com.xxd.spring.boot.demo.wubolin.interceptor;

import com.xxd.spring.boot.demo.wubolin.constant.ConstantData;
import com.xxd.spring.boot.demo.wubolin.entity.User;
import com.xxd.spring.boot.demo.wubolin.exception.MyException;
import com.xxd.spring.boot.demo.wubolin.util.UserManagerUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler ) throws Exception{
        String requestURL = request.getRequestURI();
        if(requestURL.startsWith("/studentSystem/user")){
            return true;
        }
        String authorization = request.getHeader("Authorization");
        User user = ConstantData.userMap.get(authorization);
        if(user == null){
            throw new MyException("没有权限访问，未登录","999");
        }
        UserManagerUtil.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserManagerUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
